package com.elitel.common.messageQueue;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.alibaba.fastjson.JSON;
import com.elitel.frame.main.entity.vo.ServerStatistics;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQReceiver{
    // here is use queue , limit 100 message ,if exceed , remove first
    private final Queue<ServerStatistics> queue = new LinkedList<>();
    private static final int MAX_QUANTITY = 5;

    public void receiveMessage(String message){

        System.out.println("RabbitMQReceiver receive message: " + message);
        if(StringUtils.isEmpty(message))
            return;

        ServerStatistics serverRecorder ;
        while(queue.size() >= MAX_QUANTITY){
            serverRecorder = queue.poll();
            System.out.println("excess max queue, " + queue.size() + " message: " + serverRecorder);
        }

        serverRecorder = JSON.parseObject(message, ServerStatistics.class);
        queue.offer(serverRecorder);
    }

    public ServerStatistics offer(){
        if(isEmptyQueue())
            return null;
        return queue.poll();
    }

    public boolean isEmptyQueue(){
        return queue.size() == 0;
    }

    public boolean isNotEmptyQueue(){
        return !isEmptyQueue();
    }

    public List<ServerStatistics> offerAll(){
        List<ServerStatistics> allElement = new LinkedList<>();
        int count = 0;
        while(isNotEmptyQueue() && count++ < MAX_QUANTITY){
            allElement.add(queue.poll());
            System.out.println("current count = " + count);
        }
        return allElement;
    }
}
